package com.luo.demo.scg.client.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


/**
 * REST服务 - Controller
 *
 * @author luohq
 * @date 2022-02-18
 */
@RestController
@Slf4j
public class RestSvcController {

    /**
     * 获取认证用户信息
     *
     * @param authentication 认证用户信息（由SpringSecurity自动注入）
     * @return
     */
    @GetMapping("/user_info")
    public Map<String, Object> userInfo(Authentication authentication) {
        log.info("get Authentication: class={}", authentication.getClass());
        log.info("get Authentication: {}", authentication);
        Map<String, Object> resultMap = new HashMap<>(2);
        //转换OAuth2认证信息
        OAuth2AuthenticationToken oAuth2AuthenticationToken = (OAuth2AuthenticationToken) authentication;
        //提取用户信息
        DefaultOidcUser oidcUser = (DefaultOidcUser) oAuth2AuthenticationToken.getPrincipal();
        //resultMap.put("idToken", oidcUser.getIdToken().getTokenValue());
        //resultMap.put("oidcUserInfo", oidcUser.getUserInfo().getClaims());
        //resultMap.put("oidc.claims", oidcUser.getClaims());
        //return resultMap;
        log.info("get Authentication OidcUser: {}", oidcUser);
        return oidcUser.getUserInfo().getClaims();
    }

}
